﻿using System.Collections.Generic;
using System.Linq;

namespace DataScripter.Database.SqlServer
{
    internal class SqlServerTableStructure : ITableStructure
    {
        private readonly SqlServerTableInfoProvider _tableInfoProvider;
        private IList<IForeignKey> _foreignKeys;
        private IList<FieldInfo> _primaryKeyFields;
        private IDictionary<string, FieldInfo> _fields;
        private IList<IForeignKey> _foreignKeysPointingToThisTable;

        public SqlServerTableStructure(string schemaName, string tableName, Db db)
        {
            SchemaName = schemaName;
            TableName = tableName;
            _tableInfoProvider = new SqlServerTableInfoProvider(db, SchemaName, TableName);
        }

        public string SchemaName { get; private set; }

        public string TableName { get; private set; }

        public IList<IForeignKey> ForeignKeys
        {
            get { return _foreignKeys ?? (_foreignKeys = _tableInfoProvider.GetForeignKeys().Cast<IForeignKey>().ToList()); }
        }

        public IList<IForeignKey> ForeignKeysPointingToThisTable
        {
            get { return _foreignKeysPointingToThisTable ?? (_foreignKeysPointingToThisTable = _tableInfoProvider.GetForeignKeysPointingToThisTable().Cast<IForeignKey>().ToList()); }
        }

        public IList<FieldInfo> PrimaryKeyFields
        {
            get { return _primaryKeyFields ?? (_primaryKeyFields = _tableInfoProvider.GetPrimaryKeyFields()); }
        }

        public IDictionary<string, FieldInfo> Fields
        {
            get { return _fields ?? (_fields = _tableInfoProvider.GetFields().ToDictionary(f => f.ColumnName)); }
        }

        public bool HasIdentityFields
        {
            get { return Fields.Any(f => f.Value.IsIdentity); }
        }

        public override string ToString()
        {
            return TableName;
        }
    }
}